package com.gobang.demo.service;

import com.gobang.demo.game.OnlineUserManager;
import com.gobang.demo.mapper.UserMapper;
import com.gobang.demo.model.LoginResponse;
import com.gobang.demo.model.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OnlineUserManager onlineUserManager;

    public LoginResponse login(String userName, String password, HttpServletRequest request) {
        LoginResponse response = new LoginResponse();
        User user = userMapper.selectByUsername(userName);
        if (user == null) {
            log.info("用户不存在");
            response.setMessage("用户不存在");
            return response;
        }
        if (!user.getPassword().equals(password)) {
            response.setMessage("密码错误");
            log.info("密码错误");
            return response;
        }
        if (onlineUserManager.getFromGameHall(user.getUserId()) != null ||
            onlineUserManager.getFromGameRoom(user.getUserId()) != null) {
            log.info("账号在别处登录");
            response.setMessage("账号在别处登录");
            return response;
        }
        HttpSession session = request.getSession(true);
        session.setAttribute("user",user);
        BeanUtils.copyProperties(user,response);
        response.setMessage("登录成功");
        return response;
    }

    public Integer register(String userName, String password) {
        // 0:成功 1:用户或密码为空 2:用户已存在
        if (userName.equals("") || password.equals("")) {
            log.info("用户或密码为空");
            return 1;
        }
        User user = userMapper.selectByUsername(userName);
        if (user != null) {
            log.info("用户已存在");
            return 2;
        }
        User user1 = new User();
        user1.setUserName(userName);
        user1.setPassword(password);
        int insert = userMapper.insert(userName, password);
        return 0;
    }

    public LoginResponse getUserInfo(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return null;
        }
        User user1 = userMapper.selectByUsername(user.getUserName());
        LoginResponse response = new LoginResponse();
        BeanUtils.copyProperties(user1,response);
        return response;
    }
}
